package Servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import DAO.SanPhamDAO;
import POJO.NguoiDung;
import POJO.SanPham;

/**
 * Servlet implementation class SanPhamServlet
 */
// @WebServlet("/SanPhamServlet")
public class SanPhamServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SanPhamServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub

        // get session
        HttpSession session = request.getSession();
        String err = (String) session.getAttribute("id");

        if (err == "1")
        {
            // da dang nhap
            // Lấy loại người dùng
            NguoiDung nguoiDung = (NguoiDung) session.getAttribute("nguoiDung");
            if (nguoiDung.getLoai() == 2 || nguoiDung.getLoai() == 4)
            {

                request.setAttribute("id", "2");
                ArrayList<SanPham> list = SanPhamDAO.SelectSanPhamALL();

                request.setAttribute("listSanPham", list);

                RequestDispatcher dispatcher = request
                        .getRequestDispatcher("/index.jsp");
                dispatcher.forward(request, response);
            }
            else
            {
                RequestDispatcher dispatcher = request
                        .getRequestDispatcher("/view/Permission.jsp");
                dispatcher.forward(request, response);

            }
        }
        else
        {
            response.sendRedirect("login");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        request.setAttribute("id", "2");

        String str = request.getParameter("timKiem");
        str = new String(str.getBytes("ISO-8859-1"), "UTF-8");

        ArrayList<SanPham> list = SanPhamDAO.SearchSanPhamByName(str);

        request.setAttribute("listSanPham", list);

        RequestDispatcher dispatcher = request
                .getRequestDispatcher("/index.jsp");
        dispatcher.forward(request, response);
    }

}
